/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufpe.cin.dmo4.middleware.message;

import com.google.gson.Gson;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Danilo
 */
public class JSONMarshaller implements Marshaller {

    public JSONMarshaller() {
    }

    @Override
    public RequestMessage unmarshalRequest(byte[] messageArray) {
        System.out.println(">>>>" + new String(messageArray));
        Gson gson = new Gson();
        try {
            return gson.fromJson(new String(messageArray), RequestMessage.class);
        } catch (Exception exception) {
            exception.printStackTrace();
            return null;
        }
    }

    @Override
    public byte[] marshall(Message message) {
        Gson gson = new Gson();
        return gson.toJson(message).getBytes();
    }

    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();
        list.add("Ronaldo");
        list.add(12);

        Message m = new RequestMessage(1, true, "000", "toString", list);

        Marshaller mar = new JSONMarshaller();

        byte[] b = mar.marshall(m);

        System.out.println(new String(b));

        RequestMessage m2 = mar.unmarshalRequest(b);

        System.out.println(m2.getOperation());
    }

    @Override
    public ResponseMessage unmarshalResponse(byte[] messageArray) {
        Gson gson = new Gson();
        return gson.fromJson(new String(messageArray), ResponseMessage.class);
    }

}
